package top.zhangjianyong.tools.config.mybatis;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.user.IUser;
import top.zhangjianyong.tools.user.UserHolder;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private final static Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("delFlag", 0, metaObject);

        try {
            IUser user = UserHolder.user();
            log.info("user---->" + JSONObject.toJSONString(user));
            if (user != null) {
                this.setFieldValByName("createBy", user.getId(), metaObject);
                this.setFieldValByName("updateBy", user.getId(), metaObject);
            } else {
                this.setFieldValByName("createBy", 0L, metaObject);
                this.setFieldValByName("updateBy", 0L, metaObject);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        try {
            IUser user = UserHolder.user();
            if (user != null) {
                this.setFieldValByName("updateBy", user.getId(), metaObject);
            } else {
                this.setFieldValByName("updateBy", 0L, metaObject);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            //throw new RuntimeException(e.getMessage());
        }

    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();

        System.out.println(now);
    }
}
